/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package config;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

import model.Player;

import controller.ScheduleController;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class Helper {

	public static final int WINDOWS_OS = 1;
	public static final int LINUX_OS = 2;
	public static final int MAC_OS = 3;
	public static final int OTHER_OS = 4;

	
	/** 
	 * @return a file that represents the directory this application is running from
	 */
	public static File getCurrentPath() {
		return new File(".");
	}
	
	/**
	 * Execute a mysql query and returns the result set
	 * 
	 * @param sql
	 *            the sql statement to be executed
	 * @return The query result
	 * @throws SQLException
	 *             if a database access error occurs or this method is called on
	 *             a closed Statement
	 */
	public static ResultSet localMysqlQuery(Statement stmt, String sql) throws SQLException {
		Connection conn = Settings.getLocalDatabaseConnection();
		stmt = conn.createStatement();
		ResultSet result = stmt.executeQuery(sql);
		stmt = null;
		return result;
	}

	/**
	 * Execute a mysql statement
	 * 
	 * @param sql
	 *            the sql statement to be executed
	 * @return true if the first result is a ResultSet object; false if it is an
	 *         update count or there are no results
	 * @throws SQLException
	 *             if a database access error occurs or this method is called on
	 *             a closed Statement
	 */
	public static boolean localMysqlExecute(String sql) throws SQLException {
		// Debug.msg("SQL> " + sql);
		Connection conn = Settings.getLocalDatabaseConnection();
		Statement stmt = conn.createStatement();
		boolean result = stmt.execute(sql);
		stmt.close();
		return result;
	}

	/**
	 * 
	 * @param sql
	 *            the sql statement to be executed
	 * @return the number of rows in the resultSet
	 * @throws SQLException
	 *             if a database access error occurs or this method is called on
	 *             a closed Statement
	 */
	public static int getNumberOfResults(String sql) throws SQLException {
		Connection conn = Settings.getLocalDatabaseConnection();
		if (conn == null) {
			return 0;
		}
		Statement stmt = conn.createStatement();
		ResultSet result = stmt.executeQuery(sql);
		result.last();
		int numRows = result.getRow();
		stmt.close();
		result.close();

		return numRows;
	}

	/**
	 * This function is used to scale the player
	 * 
	 * @param num
	 *            a interger that needs to be scaled
	 * @return the scaled integer based on the SCALE constant
	 */
	public static int scale(int num) {
		return (int) (num * Settings.getScale());
	}

	public static boolean hasNetworkConnection() {
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				NetworkInterface nic = interfaces.nextElement();
				if (!nic.isLoopback() && nic.isUp()) {
					return true;
				}
			}
		} catch (SocketException ex) {
			Debug.log(Helper.class.getName() + ": " + ex.getMessage(), Debug.EXCEPTION_LEVEL);
		}
		return false;
	}

	/**
	 * Java version of the PHP implode function convert an array to a String
	 * delimited by delimiter
	 * 
	 * @param ary
	 *            input array to be converted
	 * @param delim
	 *            the delimitor that will be inserted
	 * @return a string with ary element delimited by the delimiter
	 */
	public static String implode(String[] ary, String delim) {
		String out = "";
		for (int i = 0; i < ary.length; i++) {
			if (i != 0) {
				out += delim;
			}
			out += ary[i];
		}
		return out;
	}

	public static String getFileExtension(String fileName) {
		int dotPos = fileName.lastIndexOf(".");
		return fileName.substring(dotPos + 1);
	}

	public static String getFileNameWithoutExtension(String fileName) {
		int dotPos = fileName.lastIndexOf(".");
		if (dotPos < 0) {
			return fileName;
		}
		return fileName.substring(0, dotPos);
	}

	public static void main(String[] args) {
		// System.out.println(getFileNameWithoutExtension("file.dfd"));
		// System.out.println(getFileExtension("file.dfd"));
		// boolean result = recursiveDeleteFile(new File("resources"));
		Connection conn = Settings.getLocalDatabaseConnection();

		String sql = String.format("SELECT * FROM `content` WHERE `content_id`>'%1$s';", 0);
		int count = 0;
		int x;
		while (100000 > count++) {
			try {
				x = Helper.getNumberOfResults(sql);
			} catch (SQLException ex) {
				Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
			}
		}

	}

	public static Color getRandomColor() {
		Random random = new Random();
		Color randomColor = Color.getHSBColor(random.nextFloat(), 1.0F, 1.0F);
		return randomColor;
	}

	public static int getPlatform() {
		String os = System.getProperty("os.name");
		if (os.contains("Windows")) {
			return Helper.WINDOWS_OS;
		} else if (os.contains("Linux")) {
			return Helper.LINUX_OS;
		} else if (os.contains("Mac")) {
			return Helper.MAC_OS;
		} else {
			return Helper.OTHER_OS;
		}
	}

	public static String convertStreamToString(InputStream is) throws IOException {
		if (is != null) {
			Writer writer = new StringWriter();
			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);

				}
			} finally {
				is.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}

	public static void copyFromClassloaderToFileSystem(String filename, String classLoaderFileLocation) {
		// precondition: classLoaderFileLocation points to a valid location
		File destFile = new File(filename);
		OutputStream out = null;
		InputStream is = null;
		if (!destFile.exists()) {
			try {
				is = ScheduleController.class.getClassLoader().getResourceAsStream(classLoaderFileLocation);
				if (!destFile.getParentFile().exists()) {
					destFile.getParentFile().mkdirs();
				}
				out = new FileOutputStream(destFile);
				byte[] buf = new byte[1024];
				int len;

				// any of these 2 variables are null, return immediately
				if (is == null || out == null) {
					return;
				}

				while ((len = is.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
			} catch (IOException ex) {
				Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
			} finally {
				try {
					if (is != null) {
						is.close();
					}
					if (out != null) {
						out.close();
					}
				} catch (IOException ex1) {
					Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex1);
				}
			}
		}
	}

	/**
	 * @param number the number to be rounded
	 * @param precision the number of digits of precision the result will have
	 * @return double the number with the
	 */
	public static double numberToPrecision(double number, int precision) {
		long factor = (long) Math.pow(10, precision);
		double num = ((double) (Math.round((number * factor)))) / factor;
		return num;
	}
}
